#!/usr/bin/perl -w
use strict;
use Getopt::Long;
#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888
my $usage = <<"USAGE";

USAGE:

    clustal_to_fasta.pl sequences.clustal [--help]
		
		This script accepts sequences in the clustal format either in
		STDIN or on the command line and produces sequences reformatted
		in FASTA on STDOUT

USAGE

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#	line_wrap

#			puts a newline every n letters
#			n.b. Do not use for constant parameters eg "$3"

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

sub line_wrap($$)
{
	my @array;
	my $seq = $_[0];
	while (length $seq)
	{
		push @array, substr $seq, 0, $_[1], "";
	}
	return join "\n", @array;
}


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory


# optional parameters
my $help = undef;
GetOptions('help' => \$help);

die $usage if ($help);

my %sequences;
my $line_cnt = 0;

my $CLUSTAL_header = <>;
die "Error!\n\tPlease supply a valid CLUSTALW file\n$usage\n" unless $CLUSTAL_header;
die "Error!\n\tClustal files start with the words 'CLUSTAL W'\n"
	unless $CLUSTAL_header =~ /^CLUSTAL W/;

my @acc;
my %acc;
for (<>)
{
	chomp;
	next unless /^(\S+)\s+(.*)/;
	$sequences{$1} .= $2;
	push(@acc, $1) unless exists $acc{$1};
	$acc{$1} = 1;
}
for (@acc)
{
	print ">$_\n", line_wrap($sequences{$_}, 60), "\n";
}

